/****************************************************************************
 * Copyright (C) 2013 Dj_Skual
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************/
#include "NandSaveTask.hpp"
#include "../../FileOperations/Nand.hpp"
#include "../../FileOperations/fileops.h"
#include "../../Saves/DataBin/WiiSaveCrypted.h"
#include "../../Saves/SaveTools.h"

NandSaveTask::NandSaveTask(short Type, u64 title_id, std::string destpath)
	: tid(title_id)
	, destPath(destpath)
	, type(Type)
	, canceled(false)
	, window(NULL)
{
	ThreadedTaskHandler::Instance()->AddTask(this);
}

void NandSaveTask::OnCancelClick()
{
	canceled = true;
}

void NandSaveTask::Execute(void)
{
	if(!tid || destPath.empty())
	{
		End(this, -1);
		return;
	}
	
	if(type == EXTRACT_TO_DEV)
		window = new ManageProgressWindow(tr("Extracting..."));
	else if(type == COMPRESS_TO_DEV)
		window = new ManageProgressWindow(tr("Compressing..."));
	else if(type == INSTALL_TO_ENAND)
		window = new ManageProgressWindow(tr("Installing..."));
	window->Canceled.connect(this, &NandSaveTask::OnCancelClick);
	
	int result = -1;
	if(type == COMPRESS_TO_DEV)
	{
		if(destPath[destPath.size()-1] != '/')
			destPath += "/";
		destPath += SaveTools::titleText((u32)(tid >> 32),(u32)(tid & 0xFFFFFFFF));
		if(CreateSubfolder(destPath))
		{
			WiiSaveCrypted * saveCrypted = new WiiSaveCrypted();
			if(saveCrypted->Export(tid, destPath))
				result = 1;
			
			delete saveCrypted;
		}
	}
	else
	{
		std::string srcPath = SaveTools::GetNandPath(tid);
		
		if(type == INSTALL_TO_ENAND)
			destPath += fmt("/title/%08x/%08x/data", TITLE_UPPER(tid), TITLE_LOWER(tid));
		else
			destPath += fmt("/%016llx", tid);
		
		RemoveDirectory(destPath);
		
		if(Nand::ExtractDir(srcPath, destPath))
			result = 1;
	}
	
	delete window;
	
	if(canceled)
		result = 0;
	
	End(this, result);
}
